package com.example.myapplication.Teacher;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.example.myapplication.Data.Course;
import com.example.myapplication.Data.UserData;
import com.example.myapplication.R;
import com.example.myapplication.Student.SignInActivity;
import com.example.myapplication.http.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TeaPostSignActivity extends AppCompatActivity {
    private UserData userData;
    private Course course;
    private final Gson gson = new Gson();
    private EditText editStartTime, editLocation, editEndTime,editSigninCode, editMaxStudents;
    private Button btnStartSignin;
    private ImageView btnBack,ivTupian2;
    private String signCode,beginTime,endTime,courseAddr,total;

    private int code;// 响应码
    private String msg;// 提示信息
    private Object data;// 实际数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tea_post_sign);
        initView();
        // 监听发起签到按钮点击事件
        btnStartSignin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signCode = String.valueOf(editSigninCode.getText());
                beginTime = String.valueOf(editStartTime.getText());
                endTime = String.valueOf(editEndTime.getText());
                courseAddr = String.valueOf(editLocation.getText());
                total = String.valueOf(editMaxStudents.getText());
                post();
            }
        });

        // 监听返回按钮点击事件
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 关闭当前页面
            }
        });
    }

    private void initView(){
        // 初始化界面元素
        editStartTime = findViewById(R.id.edit_start_time);
        editLocation = findViewById(R.id.edit_location);
        editEndTime = findViewById(R.id.edit_end_time);
        editSigninCode = findViewById(R.id.edit_signin_code);
        editMaxStudents = findViewById(R.id.edit_max_students);
        ivTupian2 = findViewById(R.id.iv_tupian2);

        btnStartSignin = findViewById(R.id.btn_start_signin);
        btnBack = findViewById(R.id.btn_back);

        userData = (UserData)getIntent().getSerializableExtra("userData");
        course = (Course)getIntent().getSerializableExtra("course");

        Glide.with(this)
                .load(course.getCoursePhoto())//图片网址
                .apply(new RequestOptions().centerCrop()) // 可选：设置图片缩放类型
                .transition(DrawableTransitionOptions.withCrossFade()) // 可选：添加淡入淡出效果
                .into(ivTupian2);
    }

    // 处理发起签到逻辑
    private void post(){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/sign/course/teacher/initiate";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", "255cb403024d44f692620834ffc73623")
                    .add("appSecret", "12472e74638ef69e7412dbf2e818c2ae538d4")
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            // 请求体
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("beginTime", beginTime);
            bodyMap.put("courseAddr", courseAddr);
            bodyMap.put("courseId", course.getCourseId());
            bodyMap.put("courseName", course.getCourseName());
            bodyMap.put("endTime", endTime);
            bodyMap.put("signCode", signCode);
            bodyMap.put("total", total);
            bodyMap.put("userId", userData.getId());
            // 将Map转换为字符串类型加入请求体中
            String body = gson.toJson(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("info", dataResponseBody.toString());

            code = dataResponseBody.getCode();
            msg = dataResponseBody.getMsg();
            data = dataResponseBody.getData();

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    handleResponse(); // 处理响应结果
                }
            });
        }
    };
    private void handleResponse() {
        if (code == 200) {
            Toast.makeText(TeaPostSignActivity.this, "发起成功", Toast.LENGTH_LONG).show();

        } else {
            if(msg != null) {
                Toast.makeText(TeaPostSignActivity.this, msg, Toast.LENGTH_LONG).show();
            }
        }
    }


}